<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="parentId">
        <el-input
          v-model="queryParams.parentId"
          placeholder=""
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
	    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['smart:planTask:add']"
        >新增计划</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--<el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="planTaskList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="计划任务名称" prop="name"  :show-overflow-tooltip="true" width="160"></el-table-column>
      <el-table-column label="产品名称" align="center" prop="productId" sortable/>
      <el-table-column label="编制日期" align="center" prop="createDate" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编制人" align="center" prop="createUserId" />
      <el-table-column label="数量" align="center" prop="planNum" />
      <el-table-column label="完成数量" align="center" prop="num" />
      <el-table-column label="完成进度" align="center" prop="" >
        <template slot-scope="scope">
          <el-progress :text-inside="true" :stroke-width="20" :percentage="(scope.row.num/scope.row.planNum).toFixed(2)"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.smart_plan_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="开始日期" align="center" prop="startDate" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endDate" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['smart:planTask:edit']"
          >修改</el-button>
          &lt;!&ndash;计划可以新增任务&ndash;&gt;
          <el-button v-if="scope.row.type === '1'"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['smart:planTask:add']"
          >新增任务</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['smart:planTask:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>-->

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="planTaskList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="计划任务名称" prop="name"  :show-overflow-tooltip="true" width="180"></el-table-column>
      <el-table-column label="产品名称" align="center" prop="productModel.nameZh" width="180" sortable/>
      <el-table-column label="计划单开始ID" align="center" prop="code" width="180" sortable/>
      <el-table-column label="计划单批次号" align="center" prop="batch" width="180"/>
      <el-table-column label="计划数量" align="center" prop="planNum" />
      <el-table-column label="完成数量" align="center" prop="num" />
      <el-table-column label="完成进度" align="center" prop="" sortable width="180">
        <template slot-scope="scope">
          <el-progress :text-inside="true" :stroke-width="20" :percentage="(scope.row.num/scope.row.planNum*100).toFixed(2)"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="开始日期" align="center" prop="startDate" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endDate" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机构名称" align="center" prop="organizeorganazId" sortable width="180"/>
      <el-table-column label="生产状态" align="center" prop="state" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.smart_plan_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['smart:planTask:edit']"
          >修改</el-button>
          <!--计划可以新增任务-->
          <el-button v-if="scope.row.type === '1'"
                     size="mini"
                     type="text"
                     icon="el-icon-plus"
                     @click="handleAdd(scope.row)"
                     v-hasPermi="['smart:planTask:add']"
          >新增任务</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['smart:planTask:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改计划任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="父编码" prop="parentId" hidden>
          <treeselect v-model="form.parentId" :options="planTaskOptions" :normalizer="normalizer" placeholder="请选择父编码" />
        </el-form-item>
        <!--<el-form-item label="关联ID" prop="aboutId">
          <el-input v-model="form.aboutId" placeholder="请输入关联ID" />
        </el-form-item>-->
        <el-form-item label="组织编号" prop="organizeorganazId" :disabled="isDisabled">
          <treeselect v-model="form.organizeorganazId" :options="deptOptions" :show-count="true" :disabled="isDisabled" placeholder="请选择归属部门"/>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productId">
          <el-select v-model="form.productId" placeholder="请选择产品" style="width: 100%" :disabled="isDisabled">
            <el-option
              v-for="item in productModels"
              :key="item.id"
              :label="item.nameZh"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始ID" prop="code">
          <el-input v-model="form.code" placeholder="请输入开始ID" maxlength="8" @blur="updateBatch()"/>
        </el-form-item>
        <el-form-item label="批次" prop="batch">
          <el-input v-model="form.batch" readonly="true"/>
        </el-form-item>
        <el-form-item label="计划数量" prop="planNum">
          <el-input v-model="form.planNum" value="10000" placeholder="请输入计划数量" :disabled="isDisabled"/>
        </el-form-item>
        <el-form-item label="实际数量" prop="num">
          <el-input v-model="form.num" placeholder="请输入实际数量" readonly/>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate" disabled="true">
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始日期" disabled="true">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="入库状态" prop="state">
          <el-select v-model="form.state" placeholder="入库状态" style="width: 100%">
            <el-option
              v-for="dict in dict.type.smart_plan_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="执行人名称" prop="doUserId">
          <el-select v-model="form.doUserId" placeholder="请选择执行人" style="width: 100%">
            <el-option
              v-for="item in users"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPlanTask, getPlanTask, delPlanTask, addPlanTask, updatePlanTask } from "@/api/smart/planTask";
import { listModel } from "@/api/smart/model";
import { treeselect } from "@/api/system/dept";
import { listProduct } from "@/api/smart/product";
import { getUserProfile, listUser } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "PlanTask",
  dicts: ['smart_plan_state'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 计划任务表格数据
      planTaskList: [],
      // 计划任务树选项
      planTaskOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        parentId: null,
        aboutId: null,
        organizeorganazId: null,
        name: null,
        productId: null,
        code: null,
        batch: null,
        planNum: null,
        num: null,
        startDate: null,
        endDate: null,
        state: null,
        createUserId: null,
        createDate: null,
        doUserId: null,
        type: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planNum: [
          { required: true, message: "计划数量不能为空", trigger: "blur" }
        ],
        num: [
          { required: true, message: "实际数量不能为空", trigger: "blur" }
        ],
      },
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 部门树选项
      deptOptions: undefined,
      // 产品选项
      products: [],
      // 产品型号
      productModels: [],
      // 用户选项
      users: [],
      currentUser: undefined,
      /** 是否禁用*/
      isDisabled: false
    };
  },
  created() {
    this.getList();
    this.orgTreeselect();
    this.getUserList();
    this.getProductModel();
    this.getCurrentUser();
  },
  methods: {
    /** 查询计划任务列表 */
    getList() {
      this.loading = true;
      listPlanTask(this.queryParams).then(response => {
        this.planTaskList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 转换计划任务数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
	/** 查询计划任务下拉树结构 */
    getTreeselect() {
      listPlanTask().then(response => {
        this.planTaskOptions = [];
        const data = { id: 0, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.planTaskOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        aboutId: null,
        organizeorganazId: null,
        name: null,
        productId: null,
        code: null,
        batch: null,
        planNum: 10000,
        num: 0,
        startDate: new Date(),
        endDate: null,
        state: null,
        createUserId: this.currentUser.userId,
        createDate: new Date(),
        doUserId: null,
        type: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();

      this.getTreeselect();
      if (row != null && row.id) { //添加任务
        this.form.parentId = row.id;
        this.form.type = '2';
        this.isDisabled = true;
        this.form.organizeorganazId = row.organizeorganazId;
        this.form.productId = row.productId;
        this.form.planNum = row.planNum;
        this.form.num = row.num;
        // this.form.batch = row.batch;
      } else {
        this.isDisabled = false;
        this.form.parentId = 0;
        this.form.type = '1';
      }
      this.open = true;
      this.title = "添加计划任务";
      console.log(this.form);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      /*if (row != null) {
        this.form.parentId = row.id;
      }*/
      getPlanTask(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改计划任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form);
          if (this.form.id != null) {
            updatePlanTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlanTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除计划任务编号为"' + row.id + '"的数据项？').then(function() {
        return delPlanTask(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 查询用户列表 */
    getUserList() {
      listUser().then(response => {
        this.users = response.rows;
      });
    },
    /** 查询组织机构列表 */
    orgTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询产品列表 */
    getProductList() {
      listProduct().then(response => {
        this.products = response.rows;
      });
    },
    /** 查询当前用户 */
    getCurrentUser() {
      getUserProfile().then(response => {
        this.currentUser = response.data;
      });
    },
    /**
     * 根据开始Id更新批次
     */
    updateBatch: function(){
      this.form.batch = this.form.code.substring(1, 4);
    },
    /** 查询产品型号列表 */
    getProductModel() {
      listModel().then(response => {
        this.productModels = response.rows;
      });
    },
  }
};
</script>
